package com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc;

import java.nio.charset.StandardCharsets;

public class DefaultIPCChatTextSession implements IPCChatSession, IPCChatTextSessionListener.ITextReader {
    private volatile IPCChatTextSessionListener textSessionListener;
    private volatile IPCChatSessionManager sessionManager;
    private volatile int cacheSize=1024;
    public DefaultIPCChatTextSession(){
    }

    public void setTextSessionListener(IPCChatTextSessionListener textSessionListener) {
        this.textSessionListener = textSessionListener;
    }

    public IPCChatTextSessionListener getTextSessionListener() {
        return textSessionListener;
    }



    @Override
    public void onReadyToStartLoopingChat(IPCChatSessionManager sessionManager, int cacheSize) {
        this.sessionManager=sessionManager;
        this.cacheSize=cacheSize;
        if (textSessionListener!=null){
            textSessionListener.onReadyToStart(sessionManager);
        }
    }

    @Override
    public void onLoopingChat(IPCChatSessionManager sessionManager, int cacheSize) throws Exception {
        String s= readNext();//阻塞
        if (textSessionListener !=null){
            textSessionListener.onChatText(sessionManager,this,s);
        }
    }


    @Override
    public IPCChatDataType chatDataType() {
        return IPCChatDataType.TEXT;
    }


    @Override
    public String readNext() throws Exception {
        if (sessionManager!=null){
            byte[] b=sessionManager.getChatMessenger().syncReceive(cacheSize);
            String s=new String(b, StandardCharsets.UTF_8);
            return s;
        }
        return "";
    }
}
